package com.rainkaze.lifeharbor.tools.ipquery;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.rainkaze.lifeharbor.R;
import com.rainkaze.lifeharbor.databinding.ActivityToolIpQueryBinding;
import com.rainkaze.lifeharbor.tools.ipquery.model.IpPlus360Response;
import com.rainkaze.lifeharbor.tools.ipquery.model.JuheIpApiResponse;
import com.rainkaze.lifeharbor.tools.ipquery.model.JuheIpResult;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class IPQueryActivity extends AppCompatActivity {

    private static final String TAG = "IPQueryActivity";
    private static final String JUHE_API_KEY = "c71abfe217768898585750c10c423aca";
    private static final String IPPLUS360_API_URL = "https://www.ipplus360.com/getIP";
    private static final String API_BASE_URL = "http://apis.juhe.cn/ip/ipNew";

    private ActivityToolIpQueryBinding binding;

    private OkHttpClient okHttpClient;
    private Gson gson;

    // IP地址的正则表达式
    private static final Pattern IP_ADDRESS_PATTERN = Pattern.compile(
            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityToolIpQueryBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        okHttpClient = new OkHttpClient();
        gson = new Gson();

        setSupportActionBar(binding.toolbarIpQuery);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }


        // 查询IP按钮
        binding.btnQueryIp.setOnClickListener(v -> {
            String ipAddress = binding.etIpAddress.getText() != null ? binding.etIpAddress.getText().toString().trim() : "";
            if (isValidIpAddress(ipAddress)) {
                binding.tilIpAddress.setError(null);
                queryIpInformation(ipAddress);
            } else {
                binding.tilIpAddress.setError("请输入有效的IP地址");
                hideResultsAndErrors();
            }
        });

        // 获取本机IP按钮
        binding.btnFetchMyIp.setOnClickListener(v -> fetchMyPublicIp());
    }

    /**
     * 校验IP地址格式是否正确
     * @param ip IP地址字符串
     * @return 如果格式正确返回 true，否则返回 false
     */
    private boolean isValidIpAddress(String ip) {
        if (TextUtils.isEmpty(ip)) {
            return false;
        }
        Matcher matcher = IP_ADDRESS_PATTERN.matcher(ip);
        return matcher.matches();
    }

    /**
     * 获取用户本机的公网IP地址 (使用 IpPlus360 API)
     */
    private void fetchMyPublicIp() {
        showLoading(true);
        hideResultsAndErrors();

        Request request = new Request.Builder()
                .url(IPPLUS360_API_URL)
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "IpPlus360 API 调用失败: ", e);
                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoading(false);
                    showError("获取本机IP失败 (IpPlus360): " + e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;

                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        Log.e(TAG, "IpPlus360 API 响应体为空");
                        runOnUiThread(() -> {
                            if (binding == null) return;
                            showLoading(false);
                            showError("获取本机IP失败: 响应体为空 (IpPlus360)");
                        });
                        return;
                    }
                    responseBodyString = responseBody.string();
                }
                Log.d(TAG, "IpPlus360 API 响应: " + responseBodyString);

                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoading(false);
                    if (response.isSuccessful()) {
                        try {
                            IpPlus360Response apiResponse = gson.fromJson(responseBodyString, IpPlus360Response.class);

                            // 检查 API 业务逻辑是否成功
                            if (apiResponse != null && apiResponse.isSuccess() && apiResponse.getCode() == 200) {
                                String fetchedIp = apiResponse.getData();
                                if (!TextUtils.isEmpty(fetchedIp) && isValidIpAddress(fetchedIp)) {
                                    binding.etIpAddress.setText(fetchedIp);
                                    binding.tilIpAddress.setError(null);
                                    Toast.makeText(IPQueryActivity.this, "本机公网IP已获取并填入", Toast.LENGTH_SHORT).show();
                                } else {
                                    showError("获取本机IP失败: 返回IP数据无效 (" + (TextUtils.isEmpty(fetchedIp) ? "空" : fetchedIp) + ")");
                                }
                            } else if (apiResponse != null) {
                                showError("获取本机IP失败 (IpPlus360): " + apiResponse.getMsg() + " (Code: " + apiResponse.getCode() + ")");
                            } else {
                                showError("获取本机IP失败: 无法解析响应数据 (IpPlus360)");
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "IpPlus360 JSON 解析错误: ", e);
                            showError("解析本机IP响应数据时出错 (IpPlus360)");
                        }
                    } else {
                        showError("获取本机IP失败 (IpPlus360): 服务器响应 " + response.code());
                    }
                });
            }
        });
    }

    /**
     * 查询指定IP地址的详细信息 (使用聚合数据 Juhe API)
     * @param ipAddress 要查询的IP地址
     */
    private void queryIpInformation(String ipAddress) {
        // 检查 API Key 是否已配置
        if (JUHE_API_KEY.equals("YOUR_JUHE_API_KEY") || TextUtils.isEmpty(JUHE_API_KEY)) {
            showError("请先在代码中配置有效的聚合数据 API Key");
            return;
        }

        showLoading(true);
        hideResultsAndErrors();

        // 使用HttpUrl.Builder构建URL，更安全和规范
        HttpUrl.Builder urlBuilder = HttpUrl.parse(API_BASE_URL).newBuilder();
        urlBuilder.addQueryParameter("ip", ipAddress);
        urlBuilder.addQueryParameter("key", JUHE_API_KEY);

        String url = urlBuilder.build().toString();
        Log.d(TAG, "聚合数据请求 URL: " + url);

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "聚合数据 API 调用失败: ", e);
                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoading(false);
                    showError("网络请求失败: " + e.getMessage());
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                final String responseBodyString;
                try (ResponseBody responseBody = response.body()) {
                    if (responseBody == null) {
                        Log.e(TAG, "聚合数据 API 响应体为空");
                        runOnUiThread(() -> {
                            if (binding == null) return;
                            showLoading(false);
                            showError("查询IP失败: 响应体为空 (聚合)");
                        });
                        return;
                    }
                    responseBodyString = responseBody.string();
                }
                Log.d(TAG, "聚合数据 API 响应: " + responseBodyString);

                runOnUiThread(() -> {
                    if (binding == null) return;
                    showLoading(false);
                    if (response.isSuccessful()) {
                        try {
                            JuheIpApiResponse apiResponse = gson.fromJson(responseBodyString, JuheIpApiResponse.class);
                            if (apiResponse != null && "200".equals(apiResponse.getResultCode()) && apiResponse.getResult() != null) {
                                displayIpResult(apiResponse.getResult());
                            } else if (apiResponse != null) {
                                String reason = apiResponse.getReason();
                                switch (apiResponse.getErrorCode()) {
                                    case 10001: reason = "API Key无效或错误"; break;
                                    case 10002: reason = "查询不到结果或IP地址格式错误"; break;
                                    case 10003: reason = "API Key已被停用"; break;
                                    case 10004: reason = "API Key无权限"; break;
                                    case 10012: reason = "请求超过次数限制"; break;
                                }
                                showError("查询失败: " + reason + (apiResponse.getErrorCode() != 0 ? " (错误码: " + apiResponse.getErrorCode() + ")" : ""));
                            } else {
                                showError("解析响应数据失败 (聚合)");
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "聚合数据 JSON 解析错误: ", e);
                            showError("解析响应数据格式错误 (聚合)");
                        }
                    } else {
                        showError("服务器响应错误 (聚合): " + response.code());
                    }
                });
            }
        });
    }

    /**
     * 控制加载状态的显示
     * @param isLoading 是否正在加载
     */
    private void showLoading(boolean isLoading) {
        binding.pbLoading.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        // 加载时禁用按钮
        binding.btnQueryIp.setEnabled(!isLoading);
        binding.btnFetchMyIp.setEnabled(!isLoading);
    }

    /**
     * 隐藏结果卡片和错误信息文本
     */
    private void hideResultsAndErrors() {
        binding.cvIpResult.setVisibility(View.GONE);
        binding.tvErrorMessage.setVisibility(View.GONE);
    }

    /**
     * 将查询到的IP结果显示在界面上
     * @param result IP信息结果对象
     */
    private void displayIpResult(JuheIpResult result) {
        binding.tvErrorMessage.setVisibility(View.GONE);
        binding.cvIpResult.setVisibility(View.VISIBLE);
        binding.tvCountry.setText(TextUtils.isEmpty(result.getCountry()) ? "N/A" : result.getCountry());
        binding.tvProvince.setText(TextUtils.isEmpty(result.getProvince()) ? "N/A" : result.getProvince());
        binding.tvCity.setText(TextUtils.isEmpty(result.getCity()) ? "N/A" : result.getCity());
        binding.tvIsp.setText(TextUtils.isEmpty(result.getIsp()) ? "N/A" : result.getIsp());
    }

    /**
     * 显示错误信息
     * @param message 要显示的错误文本
     */
    private void showError(String message) {
        hideResultsAndErrors();
        binding.tvErrorMessage.setText(message);
        binding.tvErrorMessage.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}
